<?php

namespace app\common\http;

use app\common\exception\OtherException;
use app\common\exception\TokenException;
use think\exception\Handle;
use think\exception\ValidateException;
use think\facade\Env;
use think\facade\Log;
use think\Response;
use Throwable;

class GlobalExceptionHandle extends Handle
{
    public function render($request, Throwable $e): Response
    {
//        var_dump($e->getMessage());
        $this->report($e);
        if ($e instanceof OtherException) {
            // 业务异常处理
            return json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }

        if ($e instanceof ValidateException) {
            // 验证异常处理
            return json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => null
            ], 500);
        }

        if ($e instanceof TokenException) {
            // token异常处理
            return json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage()
            ], 401);
        }

        // 其他异常处理
        return json([
            'code' => 500,
            'msg' => Env::get('app_debug') ? $e->getMessage() : 'Internal Server Error',
            'data' => Env::get('app_debug') ? [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTrace()
            ] : null
        ], 500);
    }

    public function report(Throwable $e): void
    {
        // 异常日志记录
        Log::error(sprintf(
            "%s:%d %s (%s) %s",
            $e->getFile(),
            $e->getLine(),
            $e->getMessage(),
            get_class($e),
            $e->getTraceAsString()
        ));
    }
}